import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import xss from 'xss';
import { observer, inject } from 'mobx-react';

import './index.scss';
import User from '../../stores/user_store'
// 引入评论item模块
import CommentItem from './comment_item/index';
// 引入默认工具函数
import commFuc from '../../util/comm';
// 引入fetch函数
import postComment from '../../request/post_comment';
import getCommentList from '../../request/get_comment_list';

// 引入LoadingMore组件
import LoadingMore from '../../components/loading_more/index';

@inject((stores) => {
  const store = {
    user: stores.user,
  }
  return store
})
@observer
class Comments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      comment: '',
      commentList: [],
      page: 1,
      per_page: 2,
      hasMore: true,
      loading: true,
      timeoutId: '',
    }
    this.getComment = this.getComment.bind(this)
    this.getMoreComments = this.getMoreComments.bind(this)
    this.submitComment = this.submitComment.bind(this)
    // 控制提交按钮，间隔0.5s点击有效,
    this.timeoutId = ''
  }
  componentDidMount() {
    // 获得评论列表，默认第一页
    this.getCommentList(this.state.page, this.props.arcId, this.state.per_page);
  }
  // 获取用户输入的评论内容
  getComment(event) {
    const comment = event.target.value;
    this.setState({
      comment,
    })
  }
  // 提交评论

  // 获取已评论的列表,默认一页是10条评论
  getCommentList(page, post, per_page = 10) {
    const params = {
      page,
      post,
      per_page,
    }
    // 请求评论
    getCommentList(params).then((res) => {
      this.setState({
        commentList: res.data || [],
        hasMore: res.data.length && res.data.length === this.state.per_page,
        loading: false,
      })
    }).catch(() => {
      this.setState({
        hasMore: false,
        loading: false,
      })
    })
  }
  // 点击获得更多的评论，默认一页10条评论
  getMoreComments() {
    const params = {
      page: this.state.page + 1,
      post: this.props.arcId,
      per_page: this.state.per_page,
    }
    this.setState({
      loading: true,
    })
    // 请求更多评论
    getCommentList(params).then((res) => {
      const json = res.data
      this.setState({
        commentList: json ? this.state.commentList.concat(json) : this.state.commentList,
        hasMore: !!res.data.length && res.data.length === this.state.per_page,
        loading: false,
        page: this.state.page + 1,
      })
    })
  }
  submitComment() {
    // 控制点击提交的频率
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    this.timeoutId = setTimeout(() => {
      // 获取本地用户的cookie信息
      const { userInfo } = this.props.user;
      // 未登录点转到登录界面
      if (!userInfo.user_id) {
        this.props.history.push(`/user/login/${encodeURIComponent(this.props.match.url)}`);
        return;
      }

      const params = {
        post: this.props.arcId,
        content: xss(this.state.comment),
      }
      // 加上登录的token验证
      postComment(params).then((res) => {
        const json = res.data
        if (json.id) {
          commFuc.successTip('评论成功');
          // 清空评论textarea;
          this.refs.commentTtextarea.value = '';
          // 更新评论列表
          this.getCommentList(1, this.props.arcId);
          // 默认显示第一页
          this.setState({
            page: 1,
          })
        } else {
          commFuc.errorTip(json.message)
        }
      }).catch(() => {
        commFuc.errorTip('评论失败')
      })
    }, 500)
  }
  render() {
    return (
      <div id="comments">
        <div className="comments-container">
          <span className="comments-title">
            评论
          </span>
          <div className="comment-box">
            <textarea type="text-area" className="comment-area" placeholder="添加评论..." onChange={this.getComment} ref="commentTtextarea" />
            <button className="comment-btn" onClick={this.submitComment} >提交评论</button>
          </div>
          <span className="comments-title">
            最新评论
          </span>
          {this.state.commentList.length ?
            this.state.commentList.map(item => <CommentItem key={item.id} data={item} />) : ''
          }
          <LoadingMore
            isLoading={this.state.loading}
            hasMore={!!this.state.hasMore}
            getMore={this.getMoreComments}
          />
        </div>
      </div>
    )
  }
}
export default withRouter(Comments);
Comments.propTypes = {
  arcId: PropTypes.number,
  user: PropTypes.instanceOf(User),
  history: PropTypes.objectOf(Object),
  match: PropTypes.objectOf(Object),
}
